// 扫描所有书签并存储到本地
const getTreePromise = () => {
  return new Promise((resolve, reject) => {
    chrome.bookmarks.getTree((nodes) => {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
      } else {
        resolve(nodes);
      }
    });
  });
};

const setStoragePromise = (data) => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.set(data, () => {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
      } else {
        resolve();
      }
    });
  });
};

const initBookmarks = async () => {
  try {
    const bookmarkTreeNodes = await getTreePromise();
    
    // 安全检查
    if (!bookmarkTreeNodes || !bookmarkTreeNodes[0]) {
      console.error('No valid bookmark tree returned');
      return;
    }
    
    const bookmarks = [];
    const traverse = (node) => {
      if (node.url) bookmarks.push({
        id: node.id,
        title: node.title,
        url: node.url,
        parentId: node.parentId,
        dateAdded: node.dateAdded
      });
      if (node.children) node.children.forEach(traverse);
    };
    
    traverse(bookmarkTreeNodes[0]); // 从根节点开始遍历
    await setStoragePromise({ bookmarks });
    console.log(`成功加载 ${bookmarks.length} 个书签`);
  } catch (error) {
    console.error('加载书签时出错:', error);
  }
};

// 初始化时加载书签
initBookmarks();

// 监听书签变化事件，实时更新存储
chrome.bookmarks.onCreated.addListener(() => initBookmarks());
chrome.bookmarks.onRemoved.addListener(() => initBookmarks());
chrome.bookmarks.onChanged.addListener(() => initBookmarks());
chrome.bookmarks.onMoved.addListener(() => initBookmarks());

// 验证单个URL是否可访问
const checkUrlValidityInBackground = async (url) => {
  try {
    // 使用fetch API进行验证，service worker不受CORS限制
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 5000); // 5秒超时
    
    // 使用GET方法但只获取响应头，避免HEAD方法可能被拒绝
    const response = await fetch(url, { 
      method: 'GET',
      signal: controller.signal,
      credentials: 'omit',
      redirect: 'follow',
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
        'Range': 'bytes=0-1' // 只获取前2个字节，减少带宽消耗
      }
    });
    
    clearTimeout(timeoutId);
    return { isValid: response.ok, error: null };
  } catch (error) {
    console.log(`URL不可访问: ${url}`, error.message);
    return { isValid: false, error: error.message };
  }
};

// 保持service worker活跃的机制
let keepAliveInterval;

const startKeepAlive = () => {
  // 防止重复设置定时器
  if (keepAliveInterval) {
    clearInterval(keepAliveInterval);
  }
  
  // 每30秒执行一次轻量级操作以保持service worker活跃
  keepAliveInterval = setInterval(() => {
    try {
      // 使用存储操作作为轻量级活动
      chrome.storage.local.set({ '_keepAlive': Date.now() }, () => {
        if (chrome.runtime.lastError) {
          console.log('Keep-alive storage operation failed:', chrome.runtime.lastError);
        }
      });
    } catch (error) {
      console.log('Keep-alive operation failed:', error);
    }
  }, 30000); // 每30秒执行一次
};

// 初始化时启动keepalive
startKeepAlive();

// 消息监听器，处理来自popup或content script的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // 处理ping消息，用于激活和确认service worker正常运行
  if (message.action === 'ping') {
    console.log('接收到ping消息');
    sendResponse({ status: 'alive' });
    return true; // 保持消息通道开放
  } else if (message.action === 'reloadBookmarks') {
    console.log('接收到重新加载书签的请求');
    initBookmarks()
      .then(() => sendResponse({ success: true }))
      .catch(error => {
        console.error('重新加载书签时出错:', error);
        sendResponse({ success: false, error: error.message });
      });
    return true; // 保持消息通道开放，直到异步操作完成
  } else if (message.action === 'checkUrlValidity' && message.url) {
    console.log('接收到URL有效性检查请求:', message.url);
    checkUrlValidityInBackground(message.url)
      .then(isValid => sendResponse({ isValid }))
      .catch(error => {
        console.error('URL有效性检查时出错:', error);
        sendResponse({ isValid: false, error: error.message });
      });
    return true; // 保持消息通道开放，直到异步操作完成
  } else {
    // 如果没有匹配的动作，返回错误
    sendResponse({ isValid: false, error: 'unknown_action' });
    return true;
  }
});

// 处理长连接(port)通信
chrome.runtime.onConnect.addListener((port) => {
  console.log(`建立长连接: ${port.name}`);
  
  // 只处理书签验证相关的连接
  if (port.name === 'bookmark-validator') {
    // 监听来自端口的消息
    port.onMessage.addListener((message) => {
      console.log('通过长连接接收到消息:', message);
      
      // 处理URL有效性检查请求
      if (message.action === 'checkUrlValidity' && message.url) {
        checkUrlValidityInBackground(message.url)
          .then(isValid => {
            // 通过长连接返回结果，包含原始URL以便匹配
            try {
              port.postMessage({ url: message.url, isValid });
            } catch (error) {
              console.error('通过长连接发送响应失败:', error);
            }
          })
          .catch(error => {
            console.error('URL有效性检查时出错:', error);
            try {
              port.postMessage({ url: message.url, isValid: false, error: error.message });
            } catch (err) {
              console.error('通过长连接发送错误响应失败:', err);
            }
          });
      }
    });
    
    // 监听连接断开
    port.onDisconnect.addListener(() => {
      console.log('长连接断开');
    });
  }
});